using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Devices.Sensors;

namespace TriUan.TriUanGame.GameScreen
{
    public interface ShakeListener
    {
        void shakeStarted();
    }

    class SensorHelper
    {
        private const float DIRECTION_DELTA = 0.4f;
        private Vector3 acceleration;
        private bool receivedFirstData;
        private ShakeListener listener;

        private readonly Accelerometer acc;
        private EventHandler<SensorReadingEventArgs<AccelerometerReading>> handler;

        public SensorHelper(Accelerometer tiltsensor)
        {
            acc = tiltsensor;
        }
        public SensorHelper()
        {

        }

        public void activate(ShakeListener listener)
        {
            this.listener = listener;
            receivedFirstData = false;
            handler = dataReceived;
            acc.CurrentValueChanged += handler;
            acc.Start();
        }

        public void deactivate()
        {
            acc.CurrentValueChanged -= handler;
        }

        public void close()
        {
            try
            {
                acc.Stop();
            }
            catch (Exception e)
            {
                Console.Write(e);
            }
        }

        public Vector3 Acceleration
        {
            get
            {
                return acceleration;
            }
        }

        public void dataReceived(Object con, SensorReadingEventArgs<AccelerometerReading> e)
        {
            Vector3 a = e.SensorReading.Acceleration;
            Vector3 temp = new Vector3 { X = a.Y, Y = a.X, Z = a.Z };
            if (!receivedFirstData)
            {
                acceleration.X = temp.Y;
                acceleration.Y = temp.X;
                acceleration.Z = temp.Z;
                receivedFirstData = true;
                return;
            }
            else
            {
                if (Math.Abs(temp.Length() - Math.Abs(acceleration.Length())) > DIRECTION_DELTA)
                {
                    acceleration.X = temp.Y;
                    acceleration.Y = temp.X;
                    acceleration.Z = temp.Z;
                    listener.shakeStarted();
                }
            }

        }
    }

}
